package com.mylib.libcore.binding.viewadapter.image;


import androidx.databinding.BindingAdapter;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;


public final class ViewAdapter {
    @BindingAdapter(value = {"url", "placeholderRes"}, requireAll = false)
    public static void setImageUri(ImageView imageView, String url, int placeholderRes) {
        if (!TextUtils.isEmpty(url)) {
            //使用Glide框架加载图片
            Glide.with(imageView.getContext())
                    .load(url)
                    .apply(new RequestOptions().placeholder(placeholderRes))
                    .into(imageView);
        } else {
            imageView.setImageResource(placeholderRes);
        }
    }

    @BindingAdapter(value = {"imageRes"}, requireAll = false)
    public static void setImageRes(ImageView imageView, int imageRes) {
        imageView.setImageResource(imageRes);
    }

    @BindingAdapter(value = {"file", "placeholderRes"}, requireAll = false)
    public static void setImageFile(ImageView imageView, File file, int placeholderRes) {
        if (file != null && file.exists()) {
            //使用Glide框架加载图片
            Glide.with(imageView.getContext())
                    .load(file)
                    .apply(new RequestOptions().placeholder(placeholderRes))
                    .into(imageView);
        } else {
            imageView.setImageDrawable(null);
        }
    }
}

